<?php
namespace app\api\controller;

use think\Controller;
use app\api\validate\User as UserValidate;
use app\lib\exception\common\ParamException;
use app\lib\exception\common\MissException;
use app\lib\exception\BaseException;
use app\api\model\User as UserModel;
use think\captcha\Captcha;
use think\facade\Session;

class User extends Controller
{
	/**
	 * 谨记以下几句话：
	 * 1.一次请求的整个过程都是在控制器下的方法内发生的
	 * 2.参数验证，数据库查询，异常处理，记录日志等等，可以封装
	 * 3.异常处理要注意，每一步失败都需要抛出异常(统一抛出异常的格式)，有需要的话记录日志
	 */

    // 用户注册 
    public function register()
    {
    	// 1.获取请求参数对象
    	$params = $this->request->param();
    	// 2.验证参数(可封装)
	    	/**
	    	 * 1.准备需要验证的参数
	    	 * 2.实例化验证对象
	    	 * 3.调验证器方法验证
	    	 * 4.验证不通过则抛出异常
	    	 */
    	$data = [
    		'username' => $params['username'],
    		'email'    => $params['email'],
    		'phone'    => $params['phone'],
    		'password' => $params['password'],
    		'code'     => $params['code']
    	];
    	$validate = new UserValidate();
    	if (!$validate->scene('register')->check($data)) {
    		throw new ParamException([
    			'msg' => $validate->getError()
    		]);
        }
        // 3.验证码校验
        $captcha = new Captcha();
        if( !$captcha->check($params['code'])){
            throw new ParamException([
                'status'     => 0,
                'msg'        => '验证码错误',
                'error_code' => 400
            ]);
        }
    	// 4.查询数据库有没有此用户，如果没有就插入到数据库并返回成功结果
    	$user = UserModel::where('username', $params['username'])->find();
        if($user){
            throw new BaseException([
                'status'     => 0,
                'msg'        => '该用户名已被注册',
                'error_code' => 400
            ]);
        }
        UserModel::create([
            'username' => $params['username'],
            'email'    => $params['email'],
            'phone'    => $params['phone'],
            'password' => $params['password']
        ]);
        $result = [
            'status' => 1,
            'msg'    => '注册成功',
            'code'   => 200
        ];
        return json($result);
    }

    // 用户登录
    public function login()
    {
        // 1.先从session中获取看有没有
        if(Session::has('username')){
            $result = [
                'status' => 1,
                'msg'    => '您已登录',
                'code'   => 200
            ];
            return json($result);
        }
    	// 2.获取请求参数对象
        $params = $this->request->param();
    	// 3.验证参数
        $data = [
            'username' => $params['username'],
            'password' => $params['password'],
            'code'     => $params['code']
        ];
        $validate = new UserValidate();
        if (!$validate->scene('login')->check($data)) {
            throw new ParamException([
                'msg' => $validate->getError()
            ]);
        }
        // 4.校验验证码
        $captcha = new Captcha();
        if( !$captcha->check($params['code'])){
            throw new ParamException([
                'status'     => 0,
                'msg'        => '验证码错误',
                'error_code' => 400
            ]);
        }
    	// 5.查询数据库
        $user = UserModel::where('username', $params['username'])->find();
        if(!$user){
            throw new BaseException([
                'msg' => '该用户未注册'
            ]);
        }
        if($user->password !== $params['password']){
            throw new BaseException([
                'msg' => '用户密码错误'
            ]);
        }
        // 6.存入session
        Session::set('username',$params['username']);
        // 7.返回结果
        $result = [
            'status' => 1,
            'msg'    => '登录成功',
            'code'   => 200
        ];
        return json($result);
    }

    // 退出登陆
    public function logout()
    {
        if(!Session::has('username')){
            throw new BaseException([
                'msg' => '您未登录，请先去登录'
            ]);           
        }
        Session::delete('username');
        $result = [
            'status' => 1,
            'msg'    => '您已退出登录',
            'code'   => 200
        ];
        return json($result);
    }

    // 修改密码
    public function password()
    {
        // 1.判断是否登录
        if(!Session::has('username')){
            throw new BaseException([
                'msg' => '您未登录，请先去登录'
            ]);           
        }
        // 2.获取用户名
        $username = Session::get('username');        
        // 3.获取参数对象
        $params = $this->request->param();
        // 4.验证参数
        $data = [
        	'password' => $params['password'],
        	'new_pwd'  => $params['new_pwd']
        ];
        $validate = new UserValidate();
        if (!$validate->scene('password')->check($data)) {
            throw new ParamException([
                'msg' => $validate->getError()
            ]);
        }
        // 5.查询数据库，验证原密码是否正确
        $user = UserModel::where('username', $username)->find();
        if($params['password'] !== $user['password']){
            throw new BaseException([
                'msg' => '原密码错误'
            ]);
        }
        // 6.修改密码
        $user->password = $params['new_pwd'];
        $user->save();
        echo $user['password'];
        // 7.返回结果
        $result = [
            'status' => 1,
            'msg'    => '密码修改成功',
            'code'   => 200
        ]; 
        return $result;
    }

    // 获取验证码
    public function verify()
    {
        // 生成验证码图片
        $captcha = new Captcha();
        return $captcha->entry();
    }

    // 获取用户列表分页
    public function list()
    {
        $list = UserModel::paginate(2);
        return json($list);
    }   
}
